package com.luonan.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.luonan.mapper.UserMapper;
import com.luonan.pojo.Result;
import com.luonan.pojo.User;
import com.luonan.utils.JwtUtil;
import com.luonan.utils.Md5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static java.time.LocalDateTime.now;


@RestController
@RequestMapping("/user")
//跨域注解
@CrossOrigin
public class UserController {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;


    /**
     *      登录
     * */
    @PostMapping("/login")
    public Result login(@RequestBody User user){
        User selectUser = userMapper.selectOne(new QueryWrapper<User>().eq("username", user.getUsername()));
        if (selectUser ==null){
            return Result.error("用户不存在");
        }
        String md5_password = Md5Util.getMD5String(user.getPassword());
        if (!(selectUser.getPassword().equals(md5_password))){
            return Result.error("密码错误");
        }
        // 登录成功，赋予token
        System.out.println(selectUser.getUsername()+"登录成功...");
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", selectUser.getId());
        claims.put("username", selectUser.getUsername());
        String Token = JwtUtil.genToken(claims);

//        设计redis的存储，存储token
        ValueOperations<String, String> ValueOperations = redisTemplate.opsForValue();
        ValueOperations.set(Token,Token,1, TimeUnit.HOURS);
        return Result.success(Token);
    }

    /**
     *      注册
     * */
    @PostMapping("/register")
    public Result register(@RequestBody User user){
        User selectUser = userMapper.selectOne(new QueryWrapper<User>().eq("username", user.getUsername()));
        if (selectUser !=null){
            return Result.error("用户名已存在");
        }
        user.setPassword(Md5Util.getMD5String(user.getPassword()));
        user.setCreateTime(now());
        user.setUpdateTime(now());
        userMapper.insert(user);
        return Result.success();
    }

}
